package com.apestech.api.xml.esb.modul;

import com.apestech.api.condition.ConFieldM;
import com.apestech.api.xml.esb.ConVar;
import com.apestech.framework.db.SqlSession;
import com.apestech.framework.dictionary.modul.Table;
import com.apestech.framework.json.JSONArray;
import com.apestech.framework.json.JSONObject;
import com.apestech.framework.util.DateUtil;
import com.apestech.framework.xml.condition.modul.Condition;

import java.util.ArrayList;
import java.util.Date;

public class EsbFormCondition extends EsbFormPub {
    /*
    1）主操作界面动态生成字段
    2）主操作界面查找、固定字段的POP
    3）动态生成界面对应弹窗下条件和显示字段
    */
    private Condition condition;
    private String tabId;
    private String theme;
    private JSONObject formJson;
    private Table zxtab;
    private Table ztab;
    private Table mxtab;
    private String type;
    private JSONObject def=new JSONObject();
    private JSONObject output=new JSONObject();

    public EsbFormCondition(Condition condition, String mid, String type) throws Exception {
        this.type=type;
        this.condition=condition;
        this.formJson=condition.getFormJSON();
        SqlSession session=condition.getSession();
        theme=session.getTheme();
        tabId=condition.getTableKey().getTabName(mid);
        ztab=session.getDictTable(tabId);
        zxtab=session.getDictTable(tabId+"_EXEC");
        mxtab=session.getDictTable(tabId+"_ITEM");
    }

    public JSONArray getImportConditionField() throws Exception {  //主操作界面动态生成字段
        JSONObject param=new JSONObject();
        JSONObject ztab=new JSONObject();
        ztab.put("id","a");
        ztab.put("title","记录明细");
        param.put("tab_id_data",ztab);
        JSONObject panel=new JSONObject();
        panel.put("id",tabId);
        panel.put("title","");
        panel.put("unVisible","ID,STATE,CREATE_DATE,UPDATE_DATE,LAST_UPDATED_STAMP,CREATOR_ID,UPDATER_ID,VERSION,INNER_BUSINESS_TYPE,SCENE_ID,APPROVE_UID_ID,APPROVE_DATE,STOP_UID_ID,STOP_DATE,CONTROL_TYPE");
        panel.put("fields", addFields(zxtab,true, panel, false));
        param.put("panel_id_data",panel);

        addMxData("ITEM_F", zxtab, param, "", false);
        addMxData("ITEM_S", zxtab, param, "1_", true);
        return getConditionField(param, theme);
    }

    public JSONArray getStopConditionField() throws Exception {  //主操作界面动态生成字段
        JSONObject param=new JSONObject();
        JSONObject ztab=new JSONObject();
        ztab.put("id","a");
        ztab.put("title","记录明细");
        param.put("tab_id_data",ztab);
        JSONObject panel=new JSONObject();
        panel.put("stop",1);
        panel.put("id",tabId);
        panel.put("title","");
        panel.put("fields", addFields(zxtab, true, panel, false));
        param.put("panel_id_data",panel);

        addMxData("ITEM", zxtab, param, "", true);
        return getConditionField1(param, theme);
    }

    public JSONArray getConditionField() throws Exception {  //主操作界面动态生成字段
        JSONObject param=new JSONObject();
        JSONObject tab=new JSONObject();
        tab.put("id","a");
        tab.put("title","记录明细");
        param.put("tab_id_data",tab);

        JSONObject panel=new JSONObject();
        panel.put("id",tabId);
        panel.put("title","");
        panel.put("fields", addFields(ztab, true, panel, false));
        param.put("panel_id_data",panel);

        String mxTab="ITEMS";
        JSONObject grid=new JSONObject();
        grid.put("key",mxTab);
        grid.put("tableValid",mxTab);
        grid.put("columnDefs", addFields(mxtab, false, grid, false));
        final String[] disable = {"formState.states=='submit'"};  //formState.states=='submit'  ctx.
        String sdis="";
        for(String k: this.ztab.getField().getKeylist()){
            if("1".equals(this.ztab.getField(k).getNotNull()) && !"ID".equals(k) && !"CONTROL_TYPE".equals(k) ){
                if(!sdis.equals("")){
                    sdis=sdis+" && ";
                }
                sdis=sdis+"model."+k;
            }
        }
        //grid.put("templateOptions.disabled","!("+disable[0]+" && ("+sdis+"))");
        grid.put("templateOptions.disabled","formState.states === 'new'");
        grid.put("templateOptions.required", "true");
        param.put("grid_id_data",grid);
        return getConditionField1(param, theme);
    }

    public JSONObject getConditionFields() throws Exception {  //主操作界面动态生成字段
        JSONObject panel=new JSONObject();
        panel.put("id",tabId);
        panel.put("title","");
        panel.put("master", addFields(ztab, true, panel, false));

        String mxTab="ITEMS";
        JSONObject grid=new JSONObject();
        grid.put("key",mxTab);
        grid.put("tableValid",mxTab);
        grid.put("unVisible","ID");
        panel.put("detail", addFields(mxtab, false, grid, false));
        return panel;
    }

    private void addMxData(String mxTab, Table zxtab, JSONObject param, String no, boolean readonly)throws Exception {
//        String mxTab="ITEMS";
        if(no==null){
            no="";
        }
        JSONObject grid=new JSONObject();
        param.remove("stop");
        grid.put("key",mxTab);
        grid.put("tableValid",mxTab);
        grid.put("columnDefs", addFields(zxtab, false, grid, readonly));

        final String[] disable = {"formState.states=='submit'"};  //formState.states=='submit'  ctx.
        String sdis="";
        for(String k:zxtab.getField().getKeylist()){
            if("1".equals(zxtab.getField(k).getNotNull())){  //&& !"ID".equals(fid) && !"CONTROL_TYPE".equals(fid
                if(!sdis.equals("")){
                    sdis=sdis+" && ";
                }
                sdis=sdis+"model."+k;
            }
        }
        grid.put("templateOptions.disabled","!("+disable[0]+" && ("+sdis+"))");
        grid.put("templateOptions.required", "true");
        param.put("grid_id_"+no+"data",grid);
    }

    private JSONArray addFields(Table tab, boolean bform, JSONObject input, boolean breadonly) throws Exception {
        def=new JSONObject();
        JSONArray flist=new JSONArray();
        ArrayList<String> slist=new ArrayList<>();
        ArrayList<String> nlist=new ArrayList<>();
        String oper="pp_operate";
        ArrayList<String> mod=getOrderZd();
        if("cx".equals(type)){
            mod=getOrderCx();
        }

        for (String k : tab.getColumnList()){
            if(!tab.isField(k)){
                continue;
            }
            if(("stop".equals(type) && "STOP_ID".equals(k))||("imp".equals(type) && "IMP_ID".equals(k))){
                continue;
            }
            if(mod.contains(k)){
                continue;
            }
            String dbtype=tab.getDbType(k);
            if(dbtype.indexOf("NUMBER")>=0){
                nlist.add(k);
            } else {
                slist.add(k);
            }
        }
        slist.addAll(nlist);

        ArrayList<String> zlist=new ArrayList<>();
        for (String k: mod){
            if(tab.isField(k)){
                zlist.add(k);
            } else {
                if(k.equals("{DEF}")){
                    zlist.addAll(slist);
                }
            }
        }

        if("imp".equals(type)) {
            ConFieldM confieldM=new ConFieldM("Z_ID", tab, condition.getSession(), oper, "A", formJson);
            addFieldSingle(confieldM, true, "Z_ID", bform, input, flist);
        }

        for (String k : zlist){
            boolean bread=breadonly;
            if(isInnerField(k, type, !bform)){
                continue;
            }
            if(!tab.isField(k)){
                continue;
            }
            ConFieldM confieldM=new ConFieldM(k, tab, condition.getSession(), oper, "A", formJson);
            if("imp".equals(type) && ( "MEMO".equals(k) || "ID".equals(k) ) ){  // || "Z_ID".equals(k)
                bread=true;
            }
            if("stop".equals(type)){
                if(bform){
                   if(confieldM.getDfield(k).getDbType().indexOf("NUMBER")>=0 && confieldM.getDfield(k).getSize()>0){
                       continue;
                   }
                }
            }
            addFieldSingle(confieldM, bread, k, bform, input, flist);
            JSONObject fieldD=confieldM.getFieldD(k);
            String conqry=fieldD.getString("conqry");
            String display=fieldD.getString("display");
            for(String k1:confieldM.getTableData().getChildKey()){
                String k2=k1.replace(k+"_","");
                if(k1.indexOf("_NAME")<0 && k1.indexOf("_DESCRIPTION")<0) {
                    if(bform){
                        if(conqry.indexOf(k2)>=0){
                            addFieldSingle(confieldM, bread, k1, bform, input, flist);
                        }
                    } else {
                        if(display.indexOf(k2)>=0) {
                            addFieldSingle(confieldM, true, k1, bform, input, flist);
                        }
                    }
                }
            }
        }
        if(!bform){
            output.put("detail_default", def);
        }
        return flist;
    }



    public void addFieldSingle(ConFieldM confieldM, boolean bread, String id, boolean bform, JSONObject input, JSONArray flist)throws Exception {
        EsbFormConditionField field=null;
        if(bform){
            if("cx".equals(type)){
                field=new EsbFormConditionField("bill_query", type, confieldM, id, input);
            } else {
                field=new EsbFormConditionField("bill_oper", type, confieldM, id, input);
            }

        } else {
            if("cx".equals(type)){
                field=new EsbFormConditionField("grid_query", type, confieldM, id, input);
            } else {
                field=new EsbFormConditionField("grid_oper", type, confieldM, id, input);
            }
        }

        if("Z_ID".equals(id)){
            field.setComment("策略编码");
        }
        //field.setNotnull();  只有制單功能，此處內容為字段的NOTNULL屬性
        JSONObject param=field.getField();
        if(param!=null){
            JSONObject out=null;
            if(bform){
                out=getFormJson(param, theme);
                out.put("width", param.get("width"));
            }
            else{
                String t=param.getString("type");
                if(param.get("width")==null){
                    if(t==null) param.put("width",100);
                    else {
                        switch (t){
                            case "select":{
                                param.put("width",200);
                                break;
                            }
                            default:param.put("width",100);
                        }
                    }
                }
                if(t.toLowerCase().indexOf("number")>=0){
                    param.put("defaultValue","0");
                    def.put(id, "0");
                }
                out=getGridJson(param, theme);
                if("f_pub".equals(out.getString("cellEditor"))) out.remove("cellEditor");
            }
            if(bform && input.get("stop")==null){
                String fid=id;
                int expiring=condition.getExpiring();
                if(fid.equals("START_DATE")){
                    out.put("defaultValue", DateUtil.dateTimeToStr(new Date()));
                } else if(fid.equals("END_DATE")){
                    Date startDate=new Date();
                    Date endDate= DateUtil.addByDate(startDate,expiring);
                    out.put("defaultValue",DateUtil.dateTimeToStr(endDate));
                }
            }
            if(bread){
                JSONObject r= (JSONObject) out.get("expressionProperties");
                if(r==null){
                    r=new JSONObject();
                }
                r.put("templateOptions.disabled", "true");
                out.put("expressionProperties",r);
            }
            if("imp".equals(type) && "ID".equals(id)){
                JSONObject o=new JSONObject();
                o.putAll(out);
                o.remove("hideExpression");
                JSONObject j=new JSONObject();
                j.putAll(o);
                j.put("key","Z_ID");
                JSONObject l= (JSONObject) j.get("templateOptions");
                l.put("placeholder","请选择策略编码");
                j.put("label","策略编码");
                j.put("headerName","策略编码");
                j.put("field","Z_ID");
                j.put("templateOptions", l);
                flist.add(j);
                flist.add(o);
            } else {
                flist.add(out);
            }
        }
    }

    public JSONObject getOutput() {
        return output;
    }
}
